package top.lywivan.reggie.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.Constants;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import top.lywivan.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用于发送验证码，并将验证码存入redis
     * @param user 存储用户的手机号
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user){
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        //SMSUtils.sendMessage(user.getPhone(), code+"");
        redisTemplate.opsForValue().set(Constants.USER_CODE_REDIS_KEY+user.getPhone(),code+"",5, TimeUnit.MINUTES);
        return R.success("短信成功发送:"+code);
    }

    /**
     * 验证C端用户登陆，登陆成功后将信息存储到数据库中，并将用户信息存入session
     * @param userDto 保存用户输入的手机号和验证码
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody UserDto userDto){
        String code = (String) redisTemplate.opsForValue().get(Constants.USER_CODE_REDIS_KEY + userDto.getPhone());
        if (code==null){
            return R.error("找不到验证码/验证码已过期，请重试！");
        }
        if (!code.equals(userDto.getCode())){
            return R.error("验证码输入错误，请重试！");
        }
        redisTemplate.delete(Constants.USER_CODE_REDIS_KEY + userDto.getPhone());
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, userDto.getPhone()));
        if (one==null){
            userService.save(userDto);
        }
        session.setAttribute(Constants.USER_ID_SESSION_KEY,one==null?userDto.getId():one.getId());
        return R.success("登陆成功");
    }

    /**
     * 实现C端用户登出功能
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.invalidate();
        return R.success("退出登陆成功");
    }
}
